package com.ljyh.forum.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljyh.forum.entity.User;
import com.ljyh.forum.mapper.UserMapper;
import com.ljyh.forum.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import javax.crypto.SecretKey;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    
    @Value("${jwt.secret}")
    private String jwtSecret;
    
    @Value("${jwt.expiration}")
    private Long jwtExpiration;

    @Override
    public boolean register(String username, String password, String nickname) {
        // 检查用户名是否已存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        if (this.getOne(queryWrapper) != null) {
            return false;
        }
        
        // 创建新用户
        User user = new User();
        user.setUsername(username);
        user.setPassword(passwordEncoder.encode(password));
        user.setNickname(nickname);
        user.setRole("user");
        user.setStatus(0);
        
        return this.save(user);
    }

    @Override
    public String login(String username, String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = this.getOne(queryWrapper);
        
        if (user == null || !passwordEncoder.matches(password, user.getPassword())) {
            return null;
        }
        
        // 检查用户是否被封禁
        if (user.getStatus() == 1) {
            return null;
        }
        
        // 生成JWT token
        SecretKey key = Keys.hmacShaKeyFor(jwtSecret.getBytes());
        return Jwts.builder()
                .setSubject(user.getId().toString())
                .claim("username", user.getUsername())
                .claim("role", user.getRole())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + jwtExpiration))
                .signWith(key, SignatureAlgorithm.HS256)
                .compact();
    }

    @Override
    public User findByUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return this.getOne(queryWrapper);
    }

    @Override
    public boolean banUser(Long userId) {
        User user = this.getById(userId);
        if (user == null) {
            return false;
        }
        user.setStatus(1);
        return this.updateById(user);
    }

    @Override
    public boolean unbanUser(Long userId) {
        User user = this.getById(userId);
        if (user == null) {
            return false;
        }
        user.setStatus(0);
        return this.updateById(user);
    }

    @Override
    public User getUserInfo(Long userId) {
        User user = this.getById(userId);
        if (user != null) {
            // 移除敏感信息
            user.setPassword(null);
        }
        return user;
    }

    @Override
    public List<User> getAllUsers() {
        List<User> users = this.list();
        // 移除所有用户的密码信息
        return users.stream()
                .peek(user -> user.setPassword(null))
                .collect(Collectors.toList());
    }
}
